package com.sinosoft.cloud.access.persist;


import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2017-10-25.
 */
@Component
public class PersistService {

    /**
     * 日志管理
     */
    private final Log cLogger = LogFactory.getLog(this.getClass());

    @Value("${text.path}")
    private String textPath;

    @JmsListener(destination = "CipherText", concurrency = "1-20")
    public void persistCipherText(String msg) {

        cLogger.info("接收到密文的消息。开始持久化密文。");
        /**
         * 进行密文持久化
         */
        OutputStream os = null;

        //获取渠道代码
        int index = msg.indexOf(",");
        String bankAlias = msg.substring(0, index);

        //获取全部报文信息
        String text = msg.substring(index + 1);

        //获取当前日期字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String currentDate = sdf.format(new Date());

        //拼接文件夹名称
        String filePath = new StringBuffer(1024).append(textPath)
                .append(bankAlias).append(File.separator).append("cipherFile").append(File.separator).toString();
        File tempFile = new File(filePath);
        if (!tempFile.exists()) {
            tempFile.mkdirs();
        }

        //获取当前时间
        SimpleDateFormat sdf2 = new SimpleDateFormat("HHmmss");
        String currentTime = sdf2.format(new Date());

        //保存文件
        try {
            os = new FileOutputStream(filePath + "H" + currentTime + "-" + UUID.randomUUID() + ".xml");
            os.write(text.getBytes("UTF-8"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            cLogger.error("密文持久化出错");
            cLogger.error(ExceptionUtils.getFullStackTrace(e.fillInStackTrace()));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            cLogger.error("密文持久化出错");
            cLogger.error(ExceptionUtils.getFullStackTrace(e.fillInStackTrace()));
        } catch (IOException e) {
            e.printStackTrace();
            cLogger.error("密文持久化出错");
            cLogger.error(ExceptionUtils.getFullStackTrace(e.fillInStackTrace()));
        } finally {
            try {
                os.flush();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        cLogger.info("密文持久化完毕。");
    }

    @JmsListener(destination = "PlainText", concurrency = "1-20")
    public void persistClearText(List<String> msg) {

        /**
         * 进行密文持久化
         */
        OutputStream os = null;

        //获取银行信息
        String bankAlias = msg.get(0);
        //获取渠道信息
        String sourceType = msg.get(1);
        //获取交易编码
        String transCode = msg.get(2);
        //获取原始报文信息
        String PlainText = msg.get(3);
        //获取交易流水号
        String transNo = msg.get(4);
        //报文类型，原始报文还是返回报文
        String messageType = msg.get(5);
        //获取当前日期字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String currentDate = sdf.format(new Date());

        //拼接文件夹名称
        String filePath = new StringBuffer(1024).append(textPath)
                .append(bankAlias).append(File.separator).append(currentDate).append(File.separator)
                .append(sourceType).append(File.separator).append(transCode).append(File.separator).toString();

        //获取当前时分秒字符串
        SimpleDateFormat sdf2 = new SimpleDateFormat("HHmmss");
        String currentTime = sdf2.format(new Date());


        String fileName = new StringBuffer(1024).append(filePath).append(transNo)
                .append("-").append(messageType)
                .append("-").append(currentTime).append(".xml").toString();
        //保存文件
        try {
            FileUtils.write(new File(fileName), PlainText, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
            cLogger.error("明文持久化失败");
        }

        if ("In".equalsIgnoreCase(messageType)){
            cLogger.info("原始明文持久化完毕。" + msg.get(4));
        }
        if ("Out".equalsIgnoreCase(messageType)){
            cLogger.info("返回明文持久化完毕。" + msg.get(4));
        }
    }
}
